\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
  \ifdim\Gin@nat@width>\linewidth
    \linewidth
  \else
    \Gin@nat@width
  \fi
}
\makeatother

\definecolor{fgcolor}{rgb}{0.345, 0.345, 0.345}
\newcommand{\hlnum}[1]{\textcolor[rgb]{0.686,0.059,0.569}{#1}}%
\newcommand{\hlstr}[1]{\textcolor[rgb]{0.192,0.494,0.8}{#1}}%
\newcommand{\hlcom}[1]{\textcolor[rgb]{0.678,0.584,0.686}{\textit{#1}}}%
\newcommand{\hlopt}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlstd}[1]{\textcolor[rgb]{0.345,0.345,0.345}{#1}}%
\newcommand{\hlkwa}[1]{\textcolor[rgb]{0.161,0.373,0.58}{\textbf{#1}}}%
\newcommand{\hlkwb}[1]{\textcolor[rgb]{0.69,0.353,0.396}{#1}}%
\newcommand{\hlkwc}[1]{\textcolor[rgb]{0.333,0.667,0.333}{#1}}%
\newcommand{\hlkwd}[1]{\textcolor[rgb]{0.737,0.353,0.396}{\textbf{#1}}}%

\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
 \def\at@end@of@kframe{}%
 \ifinner\ifhmode%
  \def\at@end@of@kframe{\end{minipage}}%
  \begin{minipage}{\columnwidth}%
 \fi\fi%
 \def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
 \colorbox{shadecolor}{##1}\hskip-\fboxsep
     % There is no \\@totalrightmargin, so:
     \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
 \MakeFramed {\advance\hsize-\width
   \@totalleftmargin\z@ \linewidth\hsize
   \@setminipage}}%
 {\par\unskip\endMakeFramed%
 \at@end@of@kframe}
\makeatother

\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX

\usepackage{alltt}

\input{../labStyle}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}

\begin{document}

\license{This is a product of OpenIntro that is released under a Creative Commons Attribution-ShareAlike 3.0 Unported (\web{http://creativecommons.org/licenses/by-sa/3.0}). This lab was adapted for OpenIntro by Andrew Bray and Mine \c{C}etinkaya-Rundel from a lab written by Mark Hansen of UCLA Statistics.}

\section*{Introduction to R and RStudio}

The goal of this lab is to introduce you to R and RStudio, which you'll be using throughout the course both to learn the statistical concepts discussed in the texbook and also to analyze real data and come to informed conclusions.  To straighten out which is which: R is the name of the programming language itself and RStudio is a convenient interface.

As the labs progress, you are encouraged to explore beyond what the labs dictate; a willingness to experiment will make you a much better programmer.  Before we get to that stage, however, you need to build some basic fluency in R.  Today we begin with the fundamental building blocks of R and RStudio: the interface, reading in data, and basic commands.

\begin{figure}[h]
\centering
\includegraphics[width=4.5 in]{more/rInterface2014.png}
\end{figure}

The panel in the upper right contains your \emph{workspace} as well as a history of the commands that you've previously entered.  Any plots that you generate will show up in the panel in the lower right corner.

The panel on the left is where the action happens.  It's called the \emph{console}.  Everytime you launch RStudio, it will have the same text at the top of the console telling you the version of R that you're running.  Below that information is the \emph{prompt}.  As its name suggests, this prompt is really a request, a request for a command.  Initially, interacting with R is all about typing commands and interpreting the output. These commands and their syntax have evolved over decades (literally) and now provide what many users feel is a fairly natural way to access data and organize, describe, and invoke statistical computations.

To get you started, enter the following command at the R prompt (i.e. right after $>$ on the console).  You can either type it in manually or copy and paste it from this document.

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{source}\hlstd{(}\hlstr{"http://www.openintro.org/stat/data/arbuthnot.R"}\hlstd{)}
\end{alltt}
\end{kframe}
\end{knitrout}


This command instructs R to access the OpenIntro website and fetch some data: the Arbuthnot baptism counts for boys and girls. You should see that the workspace area in the upper righthand corner of the RStudio window now lists a data set called \hlstd{arbuthnot} that has 82 observations on 3 variables. As you interact with R, you will create a series of objects. Sometimes you load them as we have done here, and sometimes you create them yourself as the byproduct of a computation or some analysis you have performed. Note that because you are accessing data from the web, this command (and the entire assignment) will work in a computer lab, in the library, or in your dorm room; anywhere you have access to the Internet.

\subsection*{The Data: Dr. Arbuthnot's Baptism Records}

The Arbuthnot data set refers to Dr. John Arbuthnot, an 18$^{\textrm{th}}$ century physician, writer, and mathematician.  He was interested in the ratio of newborn boys to newborn girls, so he gathered the baptism records for children born in London for every year from 1629 to 1710.  We can take a look at the data by typing its name into the console.

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlstd{arbuthnot}
\end{alltt}
\end{kframe}
\end{knitrout}


What you should see are four columns of numbers, each row representing a different year: the first entry in each row is simply the row number (an index we can use to access the data from individual years if we want), the second is the year, and the third and fourth are the numbers of boys and girls baptized that year, respectively. Use the scrollbar on the right side of the console window to examine the complete data set.

Note that the row numbers in the first column are not part of Arbuthnot's data. R adds them as part of its printout to help you make visual comparisons. You can think of them as the index that you see on the left side of a spreadsheet. In fact, the comparison to a spreadsheet will generally be helpful. R has stored Arbuthnot's data in a kind of spreadsheet or table called a \emph{data frame}.

You can see the dimensions of this data frame by typing:

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{dim}\hlstd{(arbuthnot)}
\end{alltt}
\end{kframe}
\end{knitrout}


This command should output \hlstd{[1] 82 3}, indicating that there are 82 rows and 3 columns (we'll get to what the \hlstd{[1]} means in a bit), just as it says next to the object in your workspace. You can see the names of these columns (or variables) by typing:

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{names}\hlstd{(arbuthnot)}
\end{alltt}
\end{kframe}
\end{knitrout}


You should see that the data frame contains the columns \hlstd{year},  \hlstd{boys}, and  \hlstd{girls}. At this point, you might notice that many of the commands in R look a lot like functions from math class; that is, invoking R commands means supplying a function with some number of arguments. The \hlkwd{dim} and \hlkwd{names} commands, for example, each took a single argument, the name of a data frame. 

One advantage of RStudio is that it comes with a built-in data viewer. Click on the name \hlstd{arbuthnot} in the upper right window that lists the objects in your workspace. This will bring up an alternative display of the Arbuthnot counts in the upper left window. You can close the data viewer by clicking on the ``x'' in the upper lefthand corner. 

\subsection*{Some Exploration}
Let's start to examine the data a little more closely. We can access the data in a single column of a data frame separately using a command like

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlstd{arbuthnot}\hlopt{$}\hlstd{boys}
\end{alltt}
\end{kframe}
\end{knitrout}


This command will only show the number of boys baptized each year.

\begin{exercise}
What command would you use to extract just the counts of girls baptized? Try it!
\end{exercise}

Notice that the way R has printed these data is different. When we looked at the complete data frame, we saw 82 rows, one on each line of the display. These data are no longer structured in a table with other variables, so they are displayed one right after another. Objects that print out in this way are called \emph{vectors}; they represent a set of numbers. R has added numbers in [brackets] along the left side of the printout to indicate locations within the vector. For example, \hlstd{5218} follows \hlstd{[1]}, indicating that \hlstd{5218} is the first entry in the vector. And if \hlstd{[43]} starts a line, then that would mean the first number on that line would represent the 43$^{\textrm{rd}}$ entry in the vector.

R has some powerful functions for making graphics. We can create a simple plot of the number of girls baptized per year with the command

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{plot}\hlstd{(}\hlkwc{x} \hlstd{= arbuthnot}\hlopt{$}\hlstd{year,} \hlkwc{y} \hlstd{= arbuthnot}\hlopt{$}\hlstd{girls)}
\end{alltt}
\end{kframe}
\end{knitrout}


By default, R creates a scatterplot with each x,y pair indicated by an open circle. The plot itself should appear under the ``Plots'' tab of the lower right panel of RStudio. Notice that the command above again looks like a function, this time with two arguments separated by a comma.  The first argument in the plot function specifies the variable for the x-axis and the second for the y-axis. If we wanted to connect the data points with lines, we could add a third argument, the letter ``l'' for \underline{l}ine.

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{plot}\hlstd{(}\hlkwc{x} \hlstd{= arbuthnot}\hlopt{$}\hlstd{year,} \hlkwc{y} \hlstd{= arbuthnot}\hlopt{$}\hlstd{girls,} \hlkwc{type} \hlstd{=} \hlstr{"l"}\hlstd{)}
\end{alltt}
\end{kframe}
\end{knitrout}


You might wonder how you are supposed to know that it was possible to add that third argument.  Thankfully, R documents all of its functions extensively. To read what a function does and learn the arguments that are available to you, just type in a question mark followed by the name of the function that you're interested in. Try the following.

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlopt{?}\hlstd{plot}
\end{alltt}
\end{kframe}
\end{knitrout}


Notice that the help file replaces the plot  in the lower right panel. You can toggle between plots and help files using the tabs at the top of that panel.

\begin{exercise}
Is there an apparent trend in the number of girls baptized over the years?  How would you describe it?
\end{exercise}

Now, suppose we want to plot the total number of baptisms.  To compute this, we could use the fact that R is really just a big calculator. We can type in mathematical expressions like

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlnum{5218} \hlopt{+} \hlnum{4683}
\end{alltt}
\end{kframe}
\end{knitrout}


to see the total number of baptisms in 1629. We could repeat this once for each year, but there is a faster way. If we add the vector for baptisms for boys and girls, R will compute all sums simultaneously.

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlstd{arbuthnot}\hlopt{$}\hlstd{boys} \hlopt{+} \hlstd{arbuthnot}\hlopt{$}\hlstd{girls}
\end{alltt}
\end{kframe}
\end{knitrout}


What you will see are 82 numbers (in that packed display, because we aren't looking at a data frame here), each one representing the sum we're after. Take a look at a few of them and verify that they are right. Therefore, we can make a plot of the total number of baptisms per year with the command

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{plot}\hlstd{(arbuthnot}\hlopt{$}\hlstd{year, arbuthnot}\hlopt{$}\hlstd{boys} \hlopt{+} \hlstd{arbuthnot}\hlopt{$}\hlstd{girls,} \hlkwc{type} \hlstd{=} \hlstr{"l"}\hlstd{)}
\end{alltt}
\end{kframe}
\end{knitrout}


This time, note that we left out the names of the first two arguments.  We can do this because the help file shows that the default for \hlkwd{plot} is for the first argument to be the x-variable and the second argument to be the y-variable.

Similarly to how we computed the proportion of boys, we can compute the ratio of the number of boys to the number of girls baptized in 1629 with

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlnum{5218}\hlopt{/}\hlnum{4683}
\end{alltt}
\end{kframe}
\end{knitrout}


or we can act on the complete vectors with the expression

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlstd{arbuthnot}\hlopt{$}\hlstd{boys}\hlopt{/}\hlstd{arbuthnot}\hlopt{$}\hlstd{girls}
\end{alltt}
\end{kframe}
\end{knitrout}


The proportion of newborns that are boys

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlnum{5218}\hlopt{/}\hlstd{(}\hlnum{5218} \hlopt{+} \hlnum{4683}\hlstd{)}
\end{alltt}
\end{kframe}
\end{knitrout}


or this may also be computed for all years simultaneously:

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlstd{arbuthnot}\hlopt{$}\hlstd{boys}\hlopt{/}\hlstd{(arbuthnot}\hlopt{$}\hlstd{boys} \hlopt{+} \hlstd{arbuthnot}\hlopt{$}\hlstd{girls)}
\end{alltt}
\end{kframe}
\end{knitrout}


Note that with R as with your calculator, you need to be conscious of the order of operations.  Here, we want to divide the number of boys by the total number of newborns, so we have to use parentheses.  Without them, R will first do the division, then the addition, giving you something that is not a proportion.

\begin{exercise}
Now, make a plot of the proportion of boys over time. What do you see? Tip: If you use the up and down arrow keys, you can scroll through your previous commands, your so-called command history. You can also access it by clicking on the history tab in the upper right panel.  This will save you a lot of typing in the future.
\end{exercise}

Finally, in addition to simple mathematical operators like subtraction and division, you can ask R to make comparisons like greater than, $>$, less than, $<$, and equality, $==$. For example, we can ask if boys outnumber girls in each year with the expression

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlstd{arbuthnot}\hlopt{$}\hlstd{boys} \hlopt{>} \hlstd{arbuthnot}\hlopt{$}\hlstd{girls}
\end{alltt}
\end{kframe}
\end{knitrout}


This command returns 82 values of either \hlnum{TRUE} if that year had more boys than girls, or \hlnum{FALSE} if that year did not (the answer may surprise you). This output shows a different kind of data than we have considered so far. In the \hlstd{arbuthnot} data frame our values are numerical (the year, the number of boys and girls). Here, we've asked R to create \emph{logical} data, data where the values are either \hlnum{TRUE} or \hlnum{FALSE}. In general, data analysis will involve many different kinds of data types, and one reason for using R is that it is able to represent and compute with many of them.

This seems like a fair bit for your first lab, so let's stop here. To exit RStudio you can click the ``x'' in the upper right corner of the whole window.  You will be prompted to save your workspace. If you click ``save'', RStudio will save the history of your commands and all the objects in your workspace so that the next time you launch RStudio, you will see \hlstd{arbuthnot} and you will have access to the commands you typed in your previous session. For now, click ``save'', then start up RStudio again.

\vspace{2cm}

\subsection*{On Your Own}

In the previous few pages, you recreated some of the displays and preliminary analysis of Arbuthnot's baptism data. Your assignment involves repeating these steps, but for present day birth records in the United States.  Load up the present day data with the following command.

\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{source}\hlstd{(}\hlstr{"http://www.openintro.org/stat/data/present.R"}\hlstd{)}
\end{alltt}
\end{kframe}
\end{knitrout}

The data are stored in a data frame called \hlstd{present}.

\begin{enumerate}
\item What years are included in this data set? What are the dimensions of the data frame and what are the variable or column names?
\item How do these counts compare to Arbuthnot's? Are they on a similar scale?
\item Does Arbuthnot's observation about boys being born in greater proportion than girls hold up in the U.S.?
\item Make a plot that displays the boy-to-girl ratio for every year in the data set. What do you see?
\item In what year did we see the most total number of births in the U.S.? You can refer to the help files or the R reference card (\web{http://cran.r-project.org/doc/contrib/Short-refcard.pdf}) to find helpful commands. \\
\end{enumerate}

These data come from a report by the Centers for Disease Control (\web{http://www.cdc.gov/nchs/data/nvsr/nvsr53/nvsr53_20.pdf}). Check it out if you would like to read more about an analysis of sex ratios at birth in the United States. \\

That was a short introduction to R and RStudio, but we will provide you with more functions and a more complete sense of the language as the course progresses. Feel free to browse around the websites for R \web{http://www.r-project.org} and RStudio \web{http://rstudio.org} if you're interested in learning more, or find more labs for practice at \web{http://openintro.org}.

\end{document}
